package com.xju.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xju.dao.UserDao;
import com.xju.entity.User;

@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");

        // 验证用户名、密码和邮箱是否为空，并设置具体的错误信息
        StringBuilder errorMessage = new StringBuilder();
        if (username == null || username.trim().isEmpty()) {
            errorMessage.append("用户名不能为空。");
        }
        if (password == null || password.trim().isEmpty()) {
            if (errorMessage.length() > 0) {
                errorMessage.append(" ");
            }
            errorMessage.append("密码不能为空。");
        }
        if (email == null || email.trim().isEmpty()) {
            if (errorMessage.length() > 0) {
                errorMessage.append(" ");
            }
            errorMessage.append("邮箱不能为空。");
        }

        // 如果有错误信息，直接返回错误页面
        if (errorMessage.length() > 0) {
            request.setAttribute("errorMessage", errorMessage.toString());
            request.getRequestDispatcher("register.jsp").forward(request, response);
            return;
        }

        UserDao userDao = new UserDao();

        // 检查用户名是否已存在
        if (userDao.isUsernameExists(username)) {
            request.setAttribute("errorMessage", "用户名已存在，请选择其他用户名。");
            request.getRequestDispatcher("register.jsp").forward(request, response);
            return;
        }

        User user = new User(username, password, email);

        if (userDao.registerUser(user)) {
            response.sendRedirect("login.jsp");
        } else {
            request.setAttribute("errorMessage", "注册失败，请重试。");
            request.getRequestDispatcher("register.jsp").forward(request, response);
        }
    }
}
